package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

// 收货地址
@Service
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;


    // 查询收货地址列表
    @Override
    public List<Address> list() {
        // 1.构建条件  select * from address_book where user_id = ?
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());

        // 2.执行查询并返回
        return addressMapper.selectList(qw);
    }

    @Override
    public void add(Address address) {
        // 1.补全信息
        address.setUserId(UserHolder.get().getId()); // 用户id
        address.setIsDefault(0); // 是否默认地址

        // 2.保存数据库
        addressMapper.insert(address);
    }

    // 设置默认地址
    @Override
    public void setDefault(Address newAddress) {
        // 1.先把该用户所有地址设置为非默认   update address_book set is_default=0 where user_id = ?
        // 1-1 设置参数
        Address oldAddress = new Address();
        oldAddress.setIsDefault(0); // 非默认
        // 1-2 构建条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        // 1-3 执行更新
        addressMapper.update(oldAddress,qw);

        // 2.把新传递地址设置为默认
        newAddress.setIsDefault(1); // 默认
        addressMapper.updateById(newAddress);
    }

    // 查询默认地址
    @Override
    public Address findDefault() {
        // 1.构建条件 select * from address_book where user_id = 1633299848511954946 and is_default = 1
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        qw.eq(Address::getIsDefault,1);
        // 2.执行查询
        return addressMapper.selectOne(qw);
    }
}
